# encoding=utf-8
from Parents.Functions.GeneralFunction import GeneralFunction
from LBT.Resource.BaseAtt import BaseAtt
from time import sleep



class moduleOper(GeneralFunction, BaseAtt):
    """
    模块操作通用方法
    """

    def __init__(self, dr):
        self.dr = dr

    def openMoudleAndIn(self, daohangclass, modulehref, topDaohangClass='icon-menu-index'):
        '''
        通过导航的class属性和模块的href属性进入模块并切换frame
        :param daohangclass:导航class
        :param modulehref:模块href
        :param topDaohangClass:头部导航
        :return:
        '''
        self.dr.find_element_by_class_name(topDaohangClass).click()
        daohangParent = "//i[@class='{}']/../..".format(daohangclass)
        if self.dr.find_element_by_xpath(daohangParent).get_attribute('class') != 'active':
            while self.dr.find_element_by_xpath(daohangParent).get_attribute('class') != 'active':
                self.dr.find_element_by_class_name(daohangclass).click()
        return self.openNewFrame(self.find_element_by_href(self.dr, modulehref))

    def openNewFrame(self, clicker, *js):
        '''
        通过一个被点击的操作，然后对比前后frame，并切近到新打开的frame，如果传入有多的参数，那么是js，需要执行一下
        :param clicker:被操作的元素
        :param js:可能被执行的js
        :return:
        '''
        if len(js) > 0:
            return super().openNewFrame(clicker, "//iframe", js[0])
        else:
            i = 0
            isin = False
            while i < 3 and not isin:
                isin = super().openNewFrame(clicker, "//iframe")
                i += 1
            #等待三秒，页面加载
            sleep(3)
            return isin
        """
        isin=False
        oldframe = self.dr.find_elements_by_xpath("//iframe")
        clicker.click()
        if len(js)>0:
            self.dr.execute_script(js[0])
        newframe = self.dr.find_elements_by_xpath("//iframe")
        for frame in newframe:
            if frame not in oldframe:
                self.dr.switch_to.frame(frame)
                isin=True
        return isin
        """

    def close_modules(self):
        """
        根据传入的dr，关闭模块
        :param dr:
        :return:
        """
        closebtns = self.dr.find_elements_by_css_selector(self.module_close_css)
        for closebtn in closebtns:
            closebtn.click()